package com.wxy.favorites.interceptor;

import cn.hutool.core.date.DateUtil;
import com.wxy.favorites.util.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * <p>
 *
 * </p>
 *
 * @author e-Xiaoyuan.Wang
 * @since 2022/9/16 9:45
 */
@Slf4j
public class ApiLogInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("requestStartTime", System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Long requestStartTime = (Long) request.getAttribute("requestStartTime");
        String ip = IpUtils.getIp();
        Date now = new Date();
        log.info("收到请求：url = {}, method = {}, time = {}, ip = {}, times = {}ms", request.getMethod(), request.getRequestURI(),
                DateUtil.formatDateTime(now), ip, now.getTime() - requestStartTime);
    }
}
